import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TokenManager {
  //? 定义一个token变量
  String _token = '';
  String _refreshToken = '';
  //? 初始化首选项实例
  Future<SharedPreferences> _getInstance() {
    return SharedPreferences.getInstance();
  }

  //? 项目启动时初始化
  init() async {
    // 获取首选项实例
    final instance = await _getInstance();
    _token = instance.getString(GlobalVariable.TOKEN_KEY) ?? '';
    _refreshToken = instance.getString(GlobalVariable.REFRESH_TOKEN_KEY) ?? '';
  }

  //? 存储token
  setToken(String token, {String? refreshToken}) async {
    //? 获取首选项实例
    final instance = await _getInstance();
    //? 基于首选项实例存储数据
    instance.setString(GlobalVariable.TOKEN_KEY, token);
    //? 更新token
    _token = token;
    if (refreshToken != null) {
      instance.setString(GlobalVariable.REFRESH_TOKEN_KEY, refreshToken);
      //? 更新refreshToken
    }
  }

  //? 获取token
  getToken() {
    return _token ?? '';
  }

  getRefreshToken() {
    return _refreshToken ?? '';
  }

  //? 删除token
  deleteToken() async {
    //? 获取首选项实例
    final instance = await _getInstance();
    //? 基于首选项实例删除数据
    instance.remove(GlobalVariable.TOKEN_KEY);
    //? 清除token
    _token = '';
    //? 清除refreshToken
    instance.remove(GlobalVariable.REFRESH_TOKEN_KEY);
    _refreshToken = '';
  }
}

final tokenManager = TokenManager();
